﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataAccessLayer;
using DataAccessLayer.DAL;
using Common;

namespace BestBuy.ManagerViews
{
    public partial class AddProductCategory : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            User user = UserDAL.GetUserByUsername(HttpContext.Current.User.Identity.Name);
            if (user == null || user.Status != (int)UserStatus.Active || user.RoleID != (int)RoleType.Manager)
            {
                Response.Redirect("~/Account/Login.aspx");
                return;
            }
            txtName.Focus();
            LoadProductCategory();
        }

        private void LoadProductCategory()
        {
            ClearCombobox();
            List<ProductCategory> list = ManagerDAL.GetAllCategories();
            cbParent.DataSource = list;
            cbParent.DataTextField = "Name";
            cbParent.DataValueField = "ID";
            cbParent.DataBind();            
        }

        private void ClearCombobox()
        {
            for (int i = cbParent.Items.Count - 1; i > 0; i--)
            {
                cbParent.Items.RemoveAt(i);
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            using (var context = new ReverseAuctionEntities())
            {
                ProductCategory item = new ProductCategory();
                item.Name = txtName.Text.Trim();
                item.Description = txtDescription.Text.Trim();
                if (cbParent.SelectedIndex > 0)
                {
                    item.ParentID = int.Parse(cbParent.SelectedValue);
                }
                item.Active = (int)ProductCategoryStatus.Active;
                if (ManagerDAL.AddProductCategory(item))
                {
                    AddProductMessage.Show("Add Product Category success.", UserControls.MessagePanel.MessageType.Success);
                }
                else
                {
                    AddProductMessage.Show("Add Product Category error.", UserControls.MessagePanel.MessageType.Error);
                }

                ClearForm();
                LoadProductCategory();
            }
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            ClearForm();
        }

        private void ClearForm()
        {
            txtDescription.Text = "";
            txtName.Text = "";
            cbParent.SelectedIndex = 0;
        }
    }
}